package top.zhangjianyong.tools.service.api.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.zhangjianyong.tools.entity.HotVideo;
import top.zhangjianyong.tools.entity.Laji;
import top.zhangjianyong.tools.entity.UserWatched;
import top.zhangjianyong.tools.factory.LajiFactory;
import top.zhangjianyong.tools.service.api.FreeApiService;
import top.zhangjianyong.tools.service.mybatis.IHotVideoService;
import top.zhangjianyong.tools.service.mybatis.ILajiService;
import top.zhangjianyong.tools.service.mybatis.IUserWatchedService;
import top.zhangjianyong.tools.user.UserHolder;
import top.zhangjianyong.tools.utils.ApiResponse;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ： zhangjianyong
 * @date ： 2023/3/3 3:31 PM
 */
@Slf4j
@Service
public class FreeApiServiceImpl implements FreeApiService {

    @Autowired
    private IHotVideoService iHotVideoService;
    @Autowired
    private IUserWatchedService iUserWatchedService;
    @Autowired
    private ILajiService iLajiService;

    @Override
    public void douyinVideo(HttpServletResponse response) throws IOException {

        String url = douyinVideoUrl();
        response.sendRedirect(url);
    }

    @Override
    public ApiResponse douyin() {

        return ApiResponse.success(douyinVideoUrl());
    }

    private String douyinVideoUrl() {
        HttpRequest get = HttpUtil.createGet("https://zj.v.api.aa1.cn/api/video_dyv2/");
        HttpResponse execute = get.execute();
        String body = execute.body();
        JSONObject object = JSONObject.parseObject(body);
        String url = object.getString("url");
        return url;
    }

    @Override
    public ApiResponse douyin(String url, HttpServletResponse response) throws IOException {
        log.info("url:{}", url);
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse execute = get.execute();
        InputStream inputStream = execute.bodyStream();
        response.setContentType("video/mp4");
        response.setContentLengthLong(execute.contentLength());
        IoUtil.copy(inputStream, response.getOutputStream());
        return ApiResponse.success();
    }

    @Override
    public ApiResponse pic() {
        String url = "https://www.mxnzp.com/api/image/girl/list/random?app_id=rgihdrm0kslojqvm&app_secret=WnhrK251TWlUUThqaVFWbG5OeGQwdz09";
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse execute = get.execute();
        String body = execute.body();
        JSONObject json = JSONObject.parseObject(body);
        JSONArray data = json.getJSONArray("data");
        List<String> list = new ArrayList<>();
        int size = data.size();
        for (int i = 0; i < size; i++) {
            JSONObject jsonObject = data.getJSONObject(i);
            list.add(jsonObject.getString("imageUrl"));
        }

        return ApiResponse.success(list);
    }

    @Override
    public ApiResponse pic(String url, HttpServletResponse response) throws IOException {
        log.info("url:{}", url);
        HttpRequest get = HttpUtil.createGet(url);
        get.header("referer", "https://weibo.com/");
        HttpResponse execute = get.execute();
        InputStream inputStream = execute.bodyStream();
        response.setContentType(execute.header("content-type"));
        response.setContentLengthLong(execute.contentLength());
        IoUtil.copy(inputStream, response.getOutputStream());
        return ApiResponse.success();
    }

    @Override
    public ApiResponse hotVideo() {

        List<HotVideo> hotVideos = iHotVideoService.listLimit(20);

        return ApiResponse.success(hotVideos);
    }


    @Override
    public ApiResponse hotVideoUpdate(String type) {
        String url = "http://apis.juhe.cn/fapig/douyin/billboard?key=fe4442b392b793068518b47e9ac442e5&type=" + type + "&size=50";
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse execute = get.execute();
        JSONObject json = JSONObject.parseObject(execute.body());
        log.info("接口返回：{}", json);
        JSONArray result = json.getJSONArray("result");
        int size = result.size();
        for (int i = 0; i < size; i++) {
            JSONObject jsonObject = result.getJSONObject(i);
            String title = jsonObject.getString("title");
            String share_url = jsonObject.getString("share_url");
            String author = jsonObject.getString("author");
            String item_cover = jsonObject.getString("item_cover");
            Long hot_value = jsonObject.getLong("hot_value");
            String hot_words = jsonObject.getString("hot_words");
            Long play_count = jsonObject.getLong("play_count");
            Long digg_count = jsonObject.getLong("digg_count");
            Long comment_count = jsonObject.getLong("comment_count");

            HotVideo hotVideo = new HotVideo();
            hotVideo.setTitle(title);
            hotVideo.setShareUrl(share_url);
            hotVideo.setAuthor(author);
            hotVideo.setItemCover(item_cover);
            hotVideo.setHotValue(hot_value);
            hotVideo.setHotWords(hot_words);
            hotVideo.setPlayCount(play_count);
            hotVideo.setDiggCount(digg_count);
            hotVideo.setCommentCount(comment_count);
            hotVideo.setHotType(type);

            HotVideo one = iHotVideoService.qryByTitleAuthor(hotVideo);
            if (one == null) {
                iHotVideoService.save(hotVideo);
            } else {
                hotVideo.setId(one.getId());
                iHotVideoService.updateById(hotVideo);
            }
        }

        return ApiResponse.success();
    }

    @Override
    public ApiResponse hotVideoUpdateAll() {
        /*String[] type = {"hot_video", "amusement_overall", "game_console",
                "game_inf", "food_overall", "car_overall",
                "travel_overall", "sport_overall", "cospa_overall"};*/
        String[] type = {"hot_video"};

        Arrays.stream(type).forEach(this::hotVideoUpdate);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse watchHotVideo(Long videoId, Integer watchFlag) {
        Long userId = UserHolder.userIdDefaultNull();
        if (null == userId) {
            iHotVideoService.watch(videoId, watchFlag);
        } else {
            if (0 == watchFlag) {
                iUserWatchedService.del(userId, videoId);
            } else {
                UserWatched userWatched = new UserWatched(userId, videoId);
                iUserWatchedService.save(userWatched);
            }
        }

        return ApiResponse.success();
    }

    @Override
    public ApiResponse laji(String name) {
        HttpRequest get = HttpUtil.createGet("https://api.vvhan.com/api/la.ji?lj=" + name);
        HttpResponse execute = get.execute();
        String body = execute.body();
        log.info("垃圾分类返回：" + body);
        JSONObject json = JSONObject.parseObject(body);
        Laji one = iLajiService.qryByName(name);
        if (json.getBoolean("success")) {
            String sort = json.getString("sort");
            Laji laji = LajiFactory.create(name, sort);
            if (one != null) {
                laji.setId(one.getId());
                iLajiService.updateById(laji);
            } else {
                iLajiService.save(laji);
            }
            return ApiResponse.success(sort);
        } else {
            if (one != null) {
                return ApiResponse.success(one.getType());
            }
        }

        return ApiResponse.fail(body);
    }

    @Override
    public ApiResponse lajiHis() {
        List<Laji> lajis = iLajiService.listHis(20);
        return ApiResponse.success(lajis);
    }
}
